<template>
  <div class="container">
    <div class="back" @click="$router.back()">
      <i class="el-icon-back back-btn"></i>
    </div>
    <div class="left">
      <div class="customer" v-if="mode == 'ticket'">
        <div class="name" v-text="ticket.customerName" @click="$router.push({'path':'/ticket-view?customerId=' + ticket.customerId})"></div>
        <a class="email" :href="'mailto:'+ticket.customerEmail">
          <i class="el-icon-message" style="margin-right: 5px"></i>
          <span v-text="ticket.customerEmail"></span>
        </a>
        <a class="mobile" :href="'tel:'+ticket.customerMobile">
          <i class="el-icon-phone-outline"  style="margin-right: 5px"></i>
          <span v-text="ticket.customerMobile"></span>
        </a>
      </div>
      <div class="ticket-info" v-if="mode == 'ticket'">
        <div class="item">
          <div class="title">分配给</div>
          <div class="assignee">
            <div class="avatar" v-text="ticket.assigneeName?ticket.assigneeName.substr(0,1):''"></div>
            <div class="name" v-text="ticket.assigneeName"></div>
            <div class="change" @click="$refs.searchGlobal.show('people')">
              点击更换
            </div>
          </div>
        </div>
        <div class="item">
          <div class="title">状态</div>
          <div class="status">
            <el-select v-model="ticket.status" @change="changeTicketStatus">
              <el-option value="open" label="Open"></el-option>
              <el-option value="closed" label="Closed"></el-option>
            </el-select>
          </div>
        </div>
        <div class="title">工单信息</div>
        <div class="item">
          <div class="title">联系电话</div>
          <div class="mobile">
            <input v-model="ticket.customerMobile" @input="editTicketMode = true"/>
          </div>
        </div>
        <div class="item">
          <div class="title">优先级</div>
          <div class="priority">
            <el-select v-model="ticket.priority" @change="editTicketMode = true">
              <el-option :value="1" label="低"></el-option>
              <el-option :value="2" label="中"></el-option>
              <el-option :value="3" label="高"></el-option>
            </el-select>
          </div>
        </div>
        <div class="edit-icon" @click="$router.push({path:'/ticket-edit?ticketId=' + ticket.ticketId})">
          <i class="el-icon-edit-outline"></i>
        </div>
      </div>
      <div class="btn-group" v-if="editTicketMode">
        <div class="save">
          <el-button type="primary" size="small" @click="saveTicket">保存</el-button>
        </div>
        <div class="cancel">
          <el-button type="default" size="small" @click="loadTicketInfo();editTicketMode = false">取消</el-button>
        </div>
      </div>
      <div class="customer" v-if="mode == 'customer'">
        <div class="name" v-text="customer.name"></div>
        <a class="email" :href="'mailto:'+customer.email">
          <i class="el-icon-message" style="margin-right: 5px"></i>
          <span v-text="customer.email"></span>
        </a>
        <a class="mobile" :href="'tel:'+customer.mobile">
          <i class="el-icon-phone-outline"  style="margin-right: 5px"></i>
          <span v-text="customer.mobile"></span>
        </a>
      </div>
      <div v-if="mode == 'customer'" class="customer-ticket-list">
        <div class="header">工单列表</div>
        <div v-for="(item,index) in customerTicketList" style="position: relative" class="ticket-item">
          <TicketItem :options="{mode:'simple'}" :ticket="item"></TicketItem>
          <div class="item-mask" :class="{active:ticket.ticketId == item.ticketId}" @click="customerTicketSelectIndex = index;loadData(item.ticketId)"></div>
        </div>
        <div v-if="customerTicketList.length == 0" style="line-height: 50px;text-align: center;font-size: 14px;color: #666">
          暂无数据
        </div>
      </div>
    </div>
    <div class="right">
      <div class="mask" v-if="(mode == 'customer' && customerTicketList.length == 0) || ticket == null">暂无数据</div>
      <div class="header">
        <div class="title" v-text="ticket.title"></div>
        <div class="info-line">
          <div class="created" v-text="getRelativeTime(ticket.gmtModified)"></div>
        </div>
        <div class="comment-btn" :class="{active:replyMode}" @click="tabActive = 0;replyMode = !replyMode;replyEdit = ''">
          <i class="el-icon-chat-line-square"></i>
        </div>
        <div class="tool-bar">
          <div class="item" :class="{active:tabActive == 0}" @click="tabActive = 0;loadTicketReplyList()">
            反馈
            <span v-text="ticket.commentCount" v-if="ticket.commentCount>0"></span>
          </div>
          <div class="item" :class="{active:tabActive == 1}" @click="tabActive = 1;replyMode=false">
            解决方案
          </div>
          <div class="item" :class="{active:tabActive == 2}" @click="tabActive = 2;replyMode=false;loadTicketHistory()">
            历史
          </div>
        </div>
        <div class="shadow"></div>
      </div>
      <div class="comment-box" :style="{'height':replyMode?'256px':'0px'}">
        <quill-editor ref="comment" v-model="replyEdit" :options="editorOption" />
        <div class="btn-group">
          <el-button size="small" type="primary" @click="saveReply">反馈</el-button>
          <el-button size="small" type="default" @click="replyMode = false;replyEdit = ''">取消</el-button>
        </div>
      </div>
      <div class="tabs">
        <div class="tab" v-if="tabActive == 0">
          <Comment :name="item.userName"
                   :avatar="item.userName.substr(0,1)"
                   :date="getRelativeTime(item.created)"
                   v-for="(item,index) in ticketReplyList"
                   :key="index"
          >
            <div class="ql-editor" style="height: auto;padding: 0" v-html="item.content">
            </div>
          </Comment>
          <div v-if="ticketReplyList.length == 0" class="empty">
            暂无数据
          </div>
        </div>
        <div class="tab" v-if="tabActive == 1">
          <div v-if="showFinalReply">
            <el-input type="textarea" :autosize="false" v-model="ticket.finalReply">
            </el-input>
            <div class="btn-group">
              <el-button size="small" type="primary" @click="saveFinalReply">保存方案</el-button>
            </div>
          </div>
          <div v-else style="display: flex;height: 100px;align-items: center;justify-content: center">
            <div @click="showFinalReply = true" style="padding: 20px;cursor: pointer">
                <span>
                    <i class="el-icon-plus"></i>
                </span>
              <span>
                    添加方案
                </span>
            </div>
          </div>
        </div>
        <div class="tab" v-if="tabActive == 2">
          <History :history-list="ticketHistoryList"></History>
        </div>
      </div>
    </div>
    <SearchGlobal @select="globalSelect" ref="searchGlobal"></SearchGlobal>
  </div>
</template>

<script>
import {
  findById,
  saveTicket,
  findHistoryByTicketId,
  changeTicketStatus,
  assignTicket,
  findCustomerTicket
} from "@/api/ticket";
import {findReplyList,deleteReply,saveReply,saveFinalReply} from "@/api/ticket/reply";
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import EditorConfig from "@/config/editor";
import {getRelativeTime} from "@/libs/tools";
import SearchGlobal from '@/components/common/zsh-search-global'
import Comment from './comment'
import History from './history'
import {deleteById} from "@/api/knowledge";
import TicketItem from '@/view/ticket/components/ticket-item'
import {findCustomerById} from "@/api/customer";

export default {
  name: "ticket-view",
  components: {
    quillEditor,
    SearchGlobal,
    Comment,
    History,
    TicketItem
  },
  data() {
    return {
      mode:'ticket',
      customerId: null,
      customerTicketList:[],
      customerTicketSelectIndex: 0,
      replyEdit:'',
      ticket: {},
      ticketReplyList:[],
      ticketHistoryList:[],
      editorOption: EditorConfig.editorOption,
      customer: {},
      editTicketMode: false,
      replyMode:false,
      replyCopy:null,
      tabActive:0,
      showFinalReply: false
    }
  },
  created() {
    if(this.$route.query.customerId) {
      this.mode = 'customer'
      this.customerId = this.$route.query.customerId
      this.loadCustomerInfo()
      this.loadCustomerTicketList()
    }else{
      this.loadData(this.$route.query['ticketId'])
    }
  },
  methods: {
    loadCustomerInfo() {
      findCustomerById(this.customerId).then(res => {
        if(res.code == 200) {
          this.customer = res.data
        }
      })
    },
    loadCustomerTicketList() {
      findCustomerTicket(this.customerId).then(res => {
        if(res.code == 200) {
          this.customerTicketList = res.data
          if(res.data.length > 0) {
            this.loadData(res.data[0].ticketId)
          }
        }
      })
    },
    saveTicket() {
      saveTicket(this.ticket).then(res => {
        if(res.code == 200) {
          this.$message.success('保存成功')
          this.editTicketMode = false
        }
      })
    },
    changeTicketStatus(val) {
      changeTicketStatus(this.ticket.ticketId,this.ticket.oldStatus,val).then(res => {
        if(res.code == 200) {
          this.ticket.oldStatus = val
          this.$message.success('更改状态成功')
        }else{
          this.ticket.status =  this.ticket.oldStatus
        }
      })
    },
    getRelativeTime(t){
      return getRelativeTime(t)
    },
    saveFinalReply() {
      if(!this.ticket.finalReply || this.ticket.finalReply.trim().length == 0) {
        this.$confirm('是否删除解决方案?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          saveFinalReply(this.ticket.ticketId, this.ticket.finalReply).then(res => {
            if(res.code == 200) {
              this.$message.success('删除解决方案成功')
              this.showFinalReply = false
            }
          })
        }).catch(()=>{
          return
        });
        return
      }
      saveFinalReply(this.ticket.ticketId, this.ticket.finalReply).then(res => {
        if(res.code == 200) {
          this.$message.success('保存成功')
        }
      })
    },
    loadData(ticketId) {
      this.ticket.ticketId = ticketId
      this.tabActive = 0
      this.ticketHistoryList = []
      if(ticketId) {
        findById(ticketId).then(res => {
          if(res.code == 200) {
            if(res.data!=null) {
              if(res.data.finalReply) {
                this.showFinalReply = true
              }
              res.data.oldStatus = res.data.status
              this.ticket = res.data
            }else {
              this.$message.warning('工单不存在')
              setTimeout(() => {
                this.$router.replace({name:'ticket-all'})
              },1000)
            }
            this.loadTicketReplyList()
          }
        })
      }
    },
    loadTicketInfo() {
      let ticketId = this.$route.query['ticketId']
      this.ticket.ticketId = ticketId
      if(ticketId) {
        findById(ticketId).then(res => {
          if(res.code == 200) {
            if(res.data!=null) {
              res.data.oldStatus = res.data.status
              this.ticket = res.data
            }else {
              this.$message.warning('工单不存在')
              setTimeout(() => {
                this.$router.replace({name:'ticket-all'})
              },1000)
            }
          }
        })
      }
    },
    loadTicketHistory() {
      findHistoryByTicketId(this.ticket.ticketId).then(res => {
        if(res.code == 200) {
          this.ticketHistoryList = res.data
        }
      }).catch(() => {
        this.ticketHistoryList = []
      })
    },
    globalSelect(mode, item) {
      if(mode == 'people') {
        let assignee = ''
        let assigneeName = ''
        if(item.hasOwnProperty('userId')) {
          assignee = 'user_'+item.userId
          assigneeName = item.nickname
        }else {
          assignee = 'dept_'+item.deptId
          assigneeName = item.name + ' (组)'
        }
        assignTicket(this.ticket.ticketId,assignee,assigneeName).then(res => {
          if(res.code == 200) {
            this.$set(this.ticket,'assignee', assignee)
            this.$set(this.ticket,'assigneeName', assigneeName)
            this.$message.success('工单分配成功')
          }
        })
      }
    },
    loadTicketReplyList() {
      findReplyList(this.ticket.ticketId).then(res => {
        if(res.code == 200) {
          this.ticketReplyList = res.data
        }
      }).catch(() => {
        this.ticketReplyList = []
      })
    },
    saveReply() {
      let reply = {}
      reply.ticketId = this.ticket.ticketId
      reply.content = this.replyEdit
      saveReply(reply).then(res => {
        if(res.code == 200) {
          this.$message.success('回复成功')
          this.replyMode = false
          this.ticket.commentCount += 1
          if(this.mode == 'customer') {
            this.customerTicketList[this.customerTicketSelectIndex].commentCount += 1
          }
          this.loadTicketReplyList()
        }
      })
    },
  },
  watch: {
    '$route.query':function () {
      if(this.$route.query.customerId) {
        this.mode = 'customer'
        this.customerId = this.$route.query.customerId
        this.loadCustomerInfo()
        this.loadCustomerTicketList()
      }else{
        this.mode = 'ticket'
        this.loadData(this.$route.query['ticketId'])
      }
    }
  }
}
</script>

<style scoped lang="less">
.container {
  display: flex;
  width: 100%;
  height: 100%;
  flex-direction: row;
  overflow-x: auto !important;
  .back {
    padding: 15px;
    border-bottom: 1px solid #F0F0F0;
    cursor: pointer;
    &:hover {
      color: #0091ff;
    }
    .back-btn {
      font-weight: bold;
    }
    @media(max-width: 679px) {
      display: none;
    }
  }
  .left {
    width: 300px;
    flex-shrink: 0;
    box-shadow: #cdcdcd -5px 0 5px -3px;
    border-right: 1px solid #F0F0F0;
    display: flex;
    flex-direction: column;
    @media(max-width: 679px) {
      width: 200px;
    }
    position: relative;
    .btn-group {
      display: flex;
      justify-content: center;
      background: #FFFFFF;
      padding: 15px 0;
      border-top: 1px solid #F0F0F0;
      .el-button {
        width: 80px;
      }
      .save {
        margin-right: 20px;
      }
      position: absolute;
      bottom: 38px;
      left: 0;
      right: 0;
    }
    .customer {
      border-bottom: 1px dashed #E8E8E8;
      padding: 20px 30px;
      .name {
        font-size: 18px;
        color: #333333;
        padding-bottom: 10px;
        cursor: pointer;
        &:hover {
          color: #0091ff;
        }
      }
      .email,.mobile {
        font-size: 12px;
        color: #333333;
        padding-bottom: 4px;
        display: block;
        &:hover {
          color: #0091ff;
        }
      }
    }
    .customer-ticket-list {
      .header {
        font-size: 14px;padding: 15px;border-bottom: 1px solid #F0F0F0;
      }
      .ticket-item {
        .item-mask {
          position: absolute;top: 0;left: 0;right: 0;bottom: 0;
          &.active {
            background: rgba(0,0,0,.1);
            border-left: 1px solid #0091ff;
          }
          &:hover {
            cursor: pointer;
            background: rgba(0,0,0,.1);
          }
        }
      }
    }
    .ticket-info {
      position: relative;
      padding: 0px 30px 100px 30px;
      box-sizing: border-box;
      flex: 1;
      overflow: hidden;
      overflow-y: auto;
      &:hover {
        .edit-icon {
          opacity: 1;
        }
      }
      .edit-icon {
        position: absolute;
        right: 15px;
        top: 10px;
        color: #666666;
        opacity: 0;
        transition: opacity .3s;
        cursor: pointer;
        &:hover {
          color: #0091ff;
        }
      }
      .title {
        font-size: 16px;
        padding: 12px 0;
      }
      .item {
        color: #333333;
        margin-bottom: 10px;
        .title {
          font-size: 13px;
          color: #666666;
          padding: 10px 0;
        }
        .assignee {
          line-height: 30px;
          display: flex;
          color: #333333;
          font-size: 14px;
          .change {
            font-size: 12px;
            color: #666666;
            opacity: 0;
            transition: opacity .3s;
          }
          &:hover {
            cursor: pointer;
            .change {
              opacity: 1;
            }
          }
          .avatar {
            border: 1px solid #F0F0F0;
            border-radius: 50%;
            text-align: center;
            width: 30px;
            height: 30px;
            color: #666666;
            margin-right: 10px;
            line-height: 30px;
          }
          .name {
            flex: 1;
          }
        }
        .status,.priority {
          /deep/.el-select {
            width: 100%;
            .el-input {
              display: flex;
              input {
                color: #333333;
                border: none;
                transition: none;
                padding: 0;
                width: 50px;
                user-select:none;
              }
              .el-input__suffix {
                position: relative;
                .el-select__caret {
                  color: #333333;
                }
              }
            }
          }
        }
        .mobile {
          font-size: 13px;
          input {
            border: none;
            border-bottom: 1px solid transparent;
            font-size: 14px;
            padding: 4px 0;
            width: 100%;
            box-sizing: border-box;
            &:hover {
              border-bottom: 1px solid #F0F0F0;
            }
            &:focus {
              border-bottom: 1px solid #0091ff;
            }
          }
        }
      }
    }
  }
  .right {
    flex: 1;
    position: relative;
    overflow: hidden;
    overflow-y: auto;
    padding-bottom: 50px;
    min-width: 350px;
    .mask {
      position: absolute;
      z-index: 2;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: #F0F0F0;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 15px;
      color: #666666;
    }
    .header {
      position: relative;
      border-bottom: 1px solid #F0F0F0;
      padding: 25px;
      padding-bottom: 60px;
      .title {
        font-size: 23px;
      }
      .info-line {
        display: flex;
        padding: 5px 0;
        font-size: 12px;
        .created {
          &:before {
            font-family: element-icons !important;
            content: '\E71F';
            padding-right: 3px;
          }
        }
      }
      .comment-btn {
        position: absolute;
        right: 55px;
        top: 23px;
        border-radius: 50%;
        background: #FFF;
        border:1px solid rgba(0,163,254,0.6);
        font-size: 20px;
        box-shadow: 0 2px 11px 1px rgba(0,163,254,.15);
        width: 43px;
        height: 43px;
        text-align: center;
        line-height: 43px;
        color: #0091ff;
        cursor: pointer;
        &:hover,&.active {
          background: #0091ff;
          color: #FFFFFF;
        }
        @media(max-width: 679px) {
          right: 25px;
        }
      }
      .tool-bar {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background: #FFF;
        height: 40px;
        border-top: 1px solid #F0F0F0;
        border-bottom: 1px solid #F0F0F0;
      }
      .shadow {
        position: absolute;
        z-index: -2;
        width: 76%;
        bottom: 0;
        height: 10px;
        left: 12%;
        border-radius: 100px / 10px;
        box-shadow: 0 -2px 9px rgba(0,0,0,.4);
      }
    }
    .comment-box {
      position: relative;
      overflow: hidden;
      transition: height .3s;
      /deep/ .quill-editor {
        .ql-toolbar {
          border:none;
          border-bottom: 1px solid #F0F0F0;
        }
        .ql-container{
          border: none;
          height: 150px;
          border-bottom: 1px solid #F0F0F0;
        }
      }
      .btn-group {
        padding: 5px 10px;
        background: #F8F8F8;
        border-bottom: 1px solid #F0F0F0;
      }
    }
    .tool-bar {
      display: flex;
      .item {
        padding: 10px 20px;
        cursor: pointer;
        font-size: 14px;
        color: #666666;
        &.active {
          color: #0091ff;
        }
        &:hover {
          background: #F8F8F8;
        }
      }
    }
    .tabs {
      .tab {
        .empty {
          line-height: 50px;
          text-align: center;
          font-size: 14px;
          color: #666666;
        }
        /deep/.el-textarea {
          .el-textarea__inner {
            min-height: 150px !important;
            resize: none;
          }
        }
        .btn-group {
          text-align: right;
          padding: 10px;
        }
      }
    }
  }
}
</style>
